import { ref } from 'vue'

export function useInfiniteScroll(fetchDataFn, getParams, initialPage = 1) {
  const data = ref([])
  const currentPage = ref(initialPage)
  const loading = ref(false)
  const noMore = ref(false)

  const loadMore = () => {
    if (loading.value) return // 防止重复加载
    loading.value = true
    fetchDataFn({ page: currentPage.value, ...getParams })
      .then((res) => {
        if (res.result.data.length === 0) {
          noMore.value = true
          return
        }
        data.value = data.value.concat(res.result.data)
        currentPage.value++
      })
      .finally(() => {
        loading.value = false
      })
  }

  return {
    data,
    loading,
    loadMore,
    noMore,
  }
}
